package core

import (
	"context"
	"fmt"

	"github.com/louloulin/dataflare/pkg/messages"
)

// Processor 是处理器接口
type Processor interface {
	// Init 初始化处理器
	Init(config map[string]interface{}) error
	// Process 处理数据
	Process(data []byte, metadata map[string]string) ([]byte, error)
	// Close 关闭处理器
	Close() error
}

// ProcessorFactory 是创建处理器的工厂
type ProcessorFactory func() (Processor, error)

// ProcessorRegistry 是处理器注册表
type ProcessorRegistry interface {
	// RegisterProcessor 注册处理器
	RegisterProcessor(name string, factory ProcessorFactory)
	// GetProcessor 获取处理器
	GetProcessor(name string) (Processor, error)
	// ListProcessors 列出处理器
	ListProcessors() []string
}

// ProcessorRegistryImpl 是ProcessorRegistry的实现
type ProcessorRegistryImpl struct {
	// processors 是处理器工厂
	processors map[string]ProcessorFactory
}

// NewProcessorRegistry 创建一个新的处理器注册表
func NewProcessorRegistry() ProcessorRegistry {
	return &ProcessorRegistryImpl{
		processors: make(map[string]ProcessorFactory),
	}
}

// RegisterProcessor 注册处理器
func (r *ProcessorRegistryImpl) RegisterProcessor(name string, factory ProcessorFactory) {
	r.processors[name] = factory
}

// GetProcessor 获取处理器
func (r *ProcessorRegistryImpl) GetProcessor(name string) (Processor, error) {
	factory, ok := r.processors[name]
	if !ok {
		return nil, fmt.Errorf("processor not found: %s", name)
	}
	return factory()
}

// ListProcessors 列出处理器
func (r *ProcessorRegistryImpl) ListProcessors() []string {
	processors := make([]string, 0, len(r.processors))
	for name := range r.processors {
		processors = append(processors, name)
	}
	return processors
}

// ProcessorManager 是处理器管理器
type ProcessorManager interface {
	// CreateProcessor 创建处理器
	CreateProcessor(ctx context.Context, processorType string, config map[string]interface{}) (string, error)
	// ProcessData 处理数据
	ProcessData(ctx context.Context, processorID string, data []byte, metadata map[string]string) ([]byte, error)
	// CloseProcessor 关闭处理器
	CloseProcessor(ctx context.Context, processorID string) error
	// GetProcessorStatus 获取处理器状态
	GetProcessorStatus(ctx context.Context, processorID string) (string, error)
	// ListProcessors 列出处理器
	ListProcessors(ctx context.Context) ([]string, error)
}

// ProcessorManagerImpl 是ProcessorManager的实现
type ProcessorManagerImpl struct {
	// registry 是处理器注册表
	registry ProcessorRegistry
	// system 是系统
	system System
}

// NewProcessorManager 创建一个新的处理器管理器
func NewProcessorManager(registry ProcessorRegistry, system System) ProcessorManager {
	return &ProcessorManagerImpl{
		registry: registry,
		system:   system,
	}
}

// CreateProcessor 创建处理器
func (m *ProcessorManagerImpl) CreateProcessor(ctx context.Context, processorType string, config map[string]interface{}) (string, error) {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送初始化处理器命令
	response, err := workflowSupervisor.Request(&messages.InitProcessorCommand{
		ProcessorType: processorType,
		Config:        config,
	}, 30000)
	if err != nil {
		return "", err
	}

	// 解析响应
	initResponse, ok := response.(*messages.InitProcessorResponse)
	if !ok {
		return "", fmt.Errorf("unexpected response type: %T", response)
	}

	if !initResponse.Success {
		return "", fmt.Errorf("failed to create processor: %s", initResponse.Error)
	}

	return initResponse.ProcessorID, nil
}

// ProcessData 处理数据
func (m *ProcessorManagerImpl) ProcessData(ctx context.Context, processorID string, data []byte, metadata map[string]string) ([]byte, error) {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送处理数据命令
	response, err := workflowSupervisor.Request(&messages.ProcessDataCommand{
		ProcessorID: processorID,
		Data:        data,
		Metadata:    metadata,
	}, 30000)
	if err != nil {
		return nil, err
	}

	// 解析响应
	processResponse, ok := response.(*messages.ProcessDataResponse)
	if !ok {
		return nil, fmt.Errorf("unexpected response type: %T", response)
	}

	if !processResponse.Success {
		return nil, fmt.Errorf("failed to process data: %s", processResponse.Error)
	}

	return processResponse.ProcessedData, nil
}

// CloseProcessor 关闭处理器
func (m *ProcessorManagerImpl) CloseProcessor(ctx context.Context, processorID string) error {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送关闭处理器命令
	response, err := workflowSupervisor.Request(&messages.CloseProcessorCommand{
		ProcessorID: processorID,
	}, 30000)
	if err != nil {
		return err
	}

	// 解析响应
	closeResponse, ok := response.(*messages.CloseProcessorResponse)
	if !ok {
		return fmt.Errorf("unexpected response type: %T", response)
	}

	if !closeResponse.Success {
		return fmt.Errorf("failed to close processor: %s", closeResponse.Error)
	}

	return nil
}

// GetProcessorStatus 获取处理器状态
func (m *ProcessorManagerImpl) GetProcessorStatus(ctx context.Context, processorID string) (string, error) {
	// 获取工作流监督者
	workflowSupervisor := m.system.GetWorkflowSupervisor()

	// 发送获取处理器状态命令
	response, err := workflowSupervisor.Request(&messages.GetProcessorStatusCommand{
		ProcessorID: processorID,
	}, 30000)
	if err != nil {
		return "", err
	}

	// 解析响应
	statusResponse, ok := response.(*messages.GetProcessorStatusResponse)
	if !ok {
		return "", fmt.Errorf("unexpected response type: %T", response)
	}

	if !statusResponse.Success {
		return "", fmt.Errorf("failed to get processor status: %s", statusResponse.Error)
	}

	return statusResponse.Status, nil
}

// ListProcessors 列出处理器
func (m *ProcessorManagerImpl) ListProcessors(ctx context.Context) ([]string, error) {
	// 实现将在后续添加
	return nil, nil
}
